package cn.stylefeng.roses.kernel.ca.server.modular.sso.service;

import cn.stylefeng.roses.kernel.auth.api.password.PasswordStoredEncryptApi;
import cn.stylefeng.roses.kernel.ca.api.business.CaValidatePasswordApi;
import cn.stylefeng.roses.kernel.ca.api.exception.CaServerException;
import cn.stylefeng.roses.kernel.ca.api.exception.enums.CaServerExceptionEnum;
import cn.stylefeng.roses.kernel.ca.api.pojo.sso.request.SsoLoginCodeRequest;
import cn.stylefeng.roses.kernel.rule.enums.StatusEnum;
import cn.stylefeng.roses.kernel.sys.modular.user.entity.SysUser;
import cn.stylefeng.roses.kernel.sys.modular.user.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 单点登录，校验密码是否正确
 *
 * @author fengshuonan
 * @date 2021/1/27 17:24
 */
@Service
public class CaValidateService implements CaValidatePasswordApi {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private PasswordStoredEncryptApi passwordStoredEncryptApi;

    @Override
    public Long validatePassword(SsoLoginCodeRequest ssoLoginCodeRequest) {

        // 获取用户账号信息
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getAccount, ssoLoginCodeRequest.getAccount());
        lambdaQueryWrapper.select(SysUser::getUserId, SysUser::getPassword, SysUser::getPasswordSalt, SysUser::getStatusFlag);
        SysUser sysUser = sysUserService.getOne(lambdaQueryWrapper, false);

        // 1.1 如果用户信息为空
        if (sysUser == null) {
            throw new CaServerException(CaServerExceptionEnum.CA_USER_INFO_IS_NULL);
        }

        // 1.2 如果用户状态被禁用了
        if (!StatusEnum.ENABLE.getCode().equals(sysUser.getStatusFlag())) {
            throw new CaServerException(CaServerExceptionEnum.USER_STATUS_NOT_ENABLE, sysUser.getStatusFlag());
        }

        // 1.3 如果账号密码不正确
        Boolean passwordRight = passwordStoredEncryptApi.checkPasswordWithSalt(ssoLoginCodeRequest.getPassword(), sysUser.getPasswordSalt(),
                sysUser.getPassword());
        if (!passwordRight) {
            throw new CaServerException(CaServerExceptionEnum.USER_PASSWORD_WRONG);
        }

        return sysUser.getUserId();
    }
}
